package com.cskaoyan.servlet;

import com.cskaoyan.bean.MarketAdmin;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.data.AdminInfoBean;
import com.cskaoyan.bean.data.LoginUserData;
import com.cskaoyan.exception.InfoExpiredException;
import com.cskaoyan.exception.NoInfoException;
import com.cskaoyan.service.*;
import com.cskaoyan.util.*;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author stone
 * @date 2023/03/16 17:53
 */
@WebServlet("/admin/auth/*")
public class AdminAuthServlet extends WdBaseServlet {

    private AdminService adminService = new AdminServiceImpl();
    private RoleService roleService = new RoleServiceImpl();

    private BaseRespVo info(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // String token = request.getHeader(WdConstant.MARKET_TOKEN);
        // MarketAdmin info = WdTokenHolder.getInfo(token);

        MarketAdmin admin = null;
        try {
            admin = (MarketAdmin) AuthenticationUtil.getPrincipal();
        } catch (NoInfoException e) {
            return BaseRespVo.unAuthc();
        } catch (InfoExpiredException e) {
            return BaseRespVo.expired();
        }
        Map<String, Object> data = new HashMap<>();
        data.put("name", admin.getUsername());
        data.put("avatar", admin.getAvatar());

        Integer[] roleIds = admin.getRoleIds();
        Set<String> roles = roleService.queryByIds(roleIds);
        Set<String> permissions = new HashSet<>(Arrays.asList("*"));
        data.put("roles", roles);
        // NOTE
        // 这里需要转换perms结构，因为对于前端而已API形式的权限更容易理解
        data.put("perms", permissions);
        return BaseRespVo.ok(data);
    }

    private BaseRespVo login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String jsonStr = request.getReader().readLine();
        Map<String, String> map = JacksonUtil.read(jsonStr, Map.class);
        String username = map.get("username");
        String password = map.get("password");

        MarketAdmin admin = adminService.query(username, password);
        // 找不到当前用户
        if (admin == null) {
            return BaseRespVo.unAuthc();
        }
        // 能够找到当前用户
        String token = WdTokenHolder.genKey(admin);
        // todo：更新log中的日志信息
        AdminInfoBean adminInfoBean = new AdminInfoBean(username, admin.getAvatar());
        LoginUserData data = new LoginUserData(adminInfoBean, token);
        return BaseRespVo.ok(data);
    }


}
